package net.luoran.dvm.common.util;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: miao wenbin
 * @since: 2020/11/30 13:35
 * @description:
 * @version: 1.0
 */
public class JdbcUtil {
    public static List<Map<String, String>> queryDataSource(Map<String, String> afferentMap) throws SQLException {
        List<Map<String, String>> listData = null;
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            String url = afferentMap.get("url");
            String user = afferentMap.get("user");
            String password = afferentMap.get("password");
            String sql = afferentMap.get("sql");
            listData = new ArrayList<Map<String, String>>();

            //截取数据库的名称
            String jdbcType = url.substring(url.indexOf(":") + 1, url.indexOf("//") - 1);

            if (jdbcType.equals("oracle")) {
                Class.forName("oracle.jdbc.driver.OracleDriver");
            } else {//默认是mysql数据库
                Class.forName("com.mysql.cj.jdbc.Driver");
            }

            //1.加载驱动程序
            //Class.forName("com.mysql.jdbc.Driver");
            //2.获得数据库链接
            conn = DriverManager.getConnection(url, user, password);
            //3.通过数据库的连接操作数据库，实现增删改查（使用Statement类）
            pst = conn.prepareStatement(sql);
            rs = pst.executeQuery();
            ResultSetMetaData rsmt;
            //4.处理数据库的返回结果(使用ResultSet类)
            while (rs.next()) {
                rsmt = rs.getMetaData();
                Map<String, String> newMap = new HashMap<String, String>();
                for (int i = 1; i <= rsmt.getColumnCount(); i++) {
                    newMap.put(rsmt.getColumnName(i), rs.getString(rsmt.getColumnName(i)));
                }
                listData.add(newMap);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if (rs != null) {
                rs.close();
            }
            if (pst != null) {
                pst.close();
            }
            if (pst != null) {
                conn.close();
            }
        }
        return listData;
    }
}
